#include "factory.h"

//得到md5码
int get_md5data(char *file_name,char *md5_str)
{
	int ret;
	char file_path[30] ="./";
    strcat(file_path,file_name);
	ret = Compute_file_md5(file_path, md5_str);
    ERROR_CHECK(ret,-1,"compute md5");
	return 0;
}

//打开数据库
int mySqlInit(MYSQL **conn,char *query)
{
    
    char* server="localhost";//需要在调用函数前准备好数据库三件套，query填入要执行的mysql语句，conn为传入传出 参数返回执行后的值
    char* user="root";//若使用了MYSQL_RES 需要记得free_result 和closs conn
    char* password="123";
    char* database="NetDisk";//要访问的数据库名称
    int t;
    *conn=mysql_init(NULL);
    if(!mysql_real_connect(*conn,server,user,password,database,0,NULL,0))
    {
        printf("Error connecting to database:%s\n",mysql_error(*conn));
        return -1;
    }
    t=mysql_query(*conn,query);
    if(t)
    {
        printf("Error making query:%s\n",mysql_error(*conn));
        mysql_close(*conn);
        return -1;
    }
    else
    {
        return 0;
    }
} 

//拿文件code
int get_file_code(char *file_name,int belongID,int precode)
{
    int code;
    MYSQL *conn;
    MYSQL_RES *res;
    MYSQL_ROW row;
    char query[300];
    sprintf(query,"select * from filelist where filename='%s' and belongID=%d and filetype='d' and precode=%d;",file_name,belongID,precode);
    int ret=mySqlInit(&conn,query);
    if(!ret)
    {
        
    }
}

//验证用户名是否匹配
int check_usr(char* usr_name,char* salt)
{
    MYSQL *conn;
    MYSQL_RES *res;
    MYSQL_ROW row;
    char query[300]="select * from userlist;" ;
    int ret=mySqlInit(&conn,query);
    if(!ret)
    {
        res=mysql_use_result(conn);
        if(res)
        {
            while((row=mysql_fetch_row(res))!=NULL)
            {	
                if(strcmp(row[1],usr_name)==0)//匹配用户名成功,则取盐值  
                {
                    strcpy(salt,row[2]);
                    break;   
                }
            }

            if(row == NULL)//没匹配到
            {           
                printf("none of this usr Account\n");
                mysql_free_result(res);
                mysql_close(conn);
                return -1;
            }
        }
        mysql_free_result(res);
        mysql_close(conn);
        return 0;
    }
    else 
        return -1;
}

//验证密码是否匹配
int check_pwd(char* usr_name,char* usr_passwd)
{
    MYSQL *conn;
    MYSQL_RES *res;
    MYSQL_ROW row;
    char query[300]={0};
    sprintf(query,"select * from usrAdr where Usrname='%s';",usr_name);
    int ret = mySqlInit(&conn,query);
    if(!ret)
    {
        res=mysql_use_result(conn);
        if(res)
        {
            row=mysql_fetch_row(res);
            char a[200]={0};
            char b[200]={0};
            sprintf(a,"%s",row[3]);
            sprintf(b,"%s",usr_passwd);
            if(strcmp(a,b)==0)//匹配密码成功 返回0  
            {
                printf("connect success\n");
                mysql_free_result(res);
                mysql_close(conn);
                return 0;
            }
            else 
            {
                printf("fail\n");
                mysql_free_result(res);
                mysql_close(conn);
                return -1;
            }
        }
    }
}

//检查有无重名
int check_duplicates(char* usrA)
{
    MYSQL *conn;
    MYSQL_RES *res;
    MYSQL_ROW row;
    char query[300]="select * from userlist;" ;
    int ret = mySqlInit(&conn,query);
    res=mysql_use_result(conn);
    //遍历每一行
    while((row=mysql_fetch_row(res))!=NULL)
    {	
        if(strcmp(row[1],usrA)==0)//用户名已存在
        {           
            mysql_free_result(res);
            mysql_close(conn);
            return -1;
        }
    }
    mysql_free_result(res);
    mysql_close(conn);
    return 0;
}

//向数据库中插入新用户的信息
int new_user_insert(char* Username,char* salt,char* UserPasswd)
{
    MYSQL *conn;
    char query[300]={0};
    sprintf(query,"insert into userlist(ID,Username,salt,UserPasswd) value (0,'%s','%s','%s');",Username,salt,UserPasswd);
    //printf("%s\n",query);
    int ret = mySqlInit(&conn,query); 
    mysql_close(conn);
    if(!ret)
    {
	    return 0;
    }
    else 
        return -1;
}

//写日志
int usercmd_note(char *username,char *usercmd,char *cmdpath)
{
    MYSQL *conn;
    char query[300]={0};
    sprintf(query,"insert into usercmd (ID,username,usercmd,cmdpath,cmdtime) VALUE (0,'%s','%s','%s',now());",username,usercmd,cmdpath);
    int ret = mySqlInit(&conn,query);
    if(!ret)
    {
        printf("cmd note writed\n");
        mysql_close(conn);
    }
    else 
        return 0;
}

//找到code对应的precode,由返回值传出
int find_precode(int code)
{
    long precode;
    MYSQL *conn;
    MYSQL_RES *res;
    MYSQL_ROW row;
    char query[300];
    sprintf(query,"select * from filelist where code=%d;",code);
    int ret = mySqlInit(&conn,query);
    if(!ret)
    {
        res=mysql_use_result(conn);
        if(res)
        {
            row=mysql_fetch_row(res);
            char buf[1000];
            bzero(buf,sizeof(buf));
            strcpy(buf,row[0]);
            precode=atoi(buf);
            mysql_free_result(res);
            mysql_close(conn);
            return precode;
        }
    }
    else
    {
        return -1;
    }
}

//根据用户名找到ID，存入pID指向的位置
int find_ID(char *username,int *pID)
{
    MYSQL *conn;
    MYSQL_RES *res;
    MYSQL_ROW row;
    char query[300]="select * from userlist;" ;
    int ret = mySqlInit(&conn,query);
    if(!ret)
    {
        res=mysql_use_result(conn);
        if(res)
        {
            while((row=mysql_fetch_row(res))!=NULL)
            {	
                if(strcmp(row[1],username)==0)//匹配用户名成功,则取ID  
                {
                    *pID=atoi(row[0]);
                    break;   
                }
            }
        }
        mysql_free_result(res);
        mysql_close(conn);
        return 0;
    }
    else 
        return -1;
}

//找到文件对应的code,成功返回code,失败返回-1
int find_file_code(char *file_name,int belongID,int precode)
{
    int code;
    MYSQL *conn;
    MYSQL_RES *res;
    MYSQL_ROW row;
    char query[300];
    sprintf(query,"select * from filelist where filename='%s' and belongID=%d and filetype='d' and precode=%d ;",file_name,belongID,precode);
    int ret = mySqlInit(&conn,query);
    if(!ret)
    {
        res=mysql_use_result(conn);
        if(res)
        {
            row=mysql_fetch_row(res);
            if(row == NULL)//没匹配到
            {           
                mysql_free_result(res);
                mysql_close(conn);
                return -1;
            }
            else
            {	
                code=atoi(row[1]);
                mysql_free_result(res);
                mysql_close(conn);
                return code;
            }
        }
    }
}

//循环发送该目录下文件名
int ls_func(int new_fd,int code,int belongID)
{
    train_state_t* ct;
    MYSQL *conn;
    MYSQL_RES *res;
    MYSQL_ROW row;
    char query[300];
    sprintf(query,"select * from filelist where precode=%d and belongID=%d;",code,belongID);
    int ret = mySqlInit(&conn,query);
    if(!ret)
    {
        res=mysql_use_result(conn);
        if(res)
        {
            while((row=mysql_fetch_row(res))!=NULL)
            {	
                strcat(ct->buf,row[2] );
            }
            ct->data_len=strlen(ct->buf);
            ret=send_n(new_fd,&ct->data_len,sizeof(int));
            SELFFUNC_ERR_CHECK(ret,"send_n");
            ret=send_n(new_fd,&ct->buf,ct->data_len);
            SELFFUNC_ERR_CHECK(ret,"send_n");
        }
        mysql_free_result(res);
        mysql_close(conn);
        return 0;
    }
    else 
        return -1;
}

//找目标文件夹,找不到返回-1，找到返回0,并取得code,拿取md5
int find_target_file(int precode,char* filename,int belongID,char* filemd5)
{
    MYSQL *conn;
    MYSQL_RES *res;
    MYSQL_ROW row;
    char query[300];
    sprintf(query,"select * from filelist where precode=%d and belongID=%d and filename='%s' and filetype='f';",precode,belongID,filename);
    int ret = mySqlInit(&conn,query);
    res=mysql_use_result(conn);
    if((row=mysql_fetch_row(res))==NULL)//不存在
    {
        mysql_free_result(res);
        mysql_close(conn);
        return -1;
    }
    strcpy(filemd5,row[5]);
    mysql_free_result(res);
    mysql_close(conn);
    return 0;
}

//删除文件
int delete_file(int precode,char* filename,int belongID)
{
    MYSQL *conn;
    MYSQL_RES *res;
    MYSQL_ROW row;
    char query[300];
    sprintf(query,"delete from filelist where precode=%d and belongID=%d and filename='%s' and filetype='f';",precode,belongID,filename);
    int ret = mySqlInit(&conn,query);
    mysql_close(conn);
    return 0;
}

//被remove的文件linknum减1
void linknum_reduce(char* filemd5)
{
    MYSQL *conn;
    MYSQL_RES *res;
    MYSQL_ROW row;
    char query[300];
    sprintf(query,"update filepool set linknum=linknum-1 where filemd5='%s';",filemd5);
    int ret = mySqlInit(&conn,query);
    mysql_close(conn);
}

//删除文件池表项
void delete_filepool(char* filemd5)
{
    MYSQL *conn;
    MYSQL_RES *res;
    MYSQL_ROW row;
    char query1[300];
    char query2[300];
    sprintf(query1,"select * from filepool where filemd5='%s' and linknum=0;",filemd5);
    int ret = mySqlInit(&conn,query1);
    res=mysql_use_result(conn);
    if((row=mysql_fetch_row(res))!=NULL)//找到
    {
        char deletepath[1000];
        sprintf(deletepath,"file_pool/%s",filemd5);
        remove(deletepath);
        printf("\nA file source has been deleted!!\n");
    }
    mysql_free_result(res);
    mysql_close(conn);

    sprintf(query2,"delete from filepool where filemd5='%s' and linknum=0;",filemd5);
    ret = mySqlInit(&conn,query2);
    if(ret!=-1)
    {
        printf("\nA file_pool member delete.\n");
    }
    mysql_close(conn);
}

//用户登陆记录
int userlogin_note(char *username)
{
    MYSQL *conn;
    char query[300];
    sprintf(query,"insert into userlogin(ID,Username,loginTime) value (0,'%s',now());",username) ;
    int ret = mySqlInit(&conn,query);
    if(!ret)
        mysql_close(conn);
    else 
        return 0;
}

//根据token找到用户名，成功返回0，失败返回-1
int get_salt_to_username(char* username,char* salt)
{
    MYSQL *conn;
    MYSQL_RES *res;
    MYSQL_ROW row;
    char query[300];
    sprintf(query,"select * from userlist where salt='%s';",salt);
    printf("%s\n",query);
    int ret = mySqlInit(&conn,query);
    res=mysql_use_result(conn);
    if((row=mysql_fetch_row(res))!=NULL)//salt存在,获取username
    {
        strncpy(username,row[1],sizeof(username));
        mysql_free_result(res);
        mysql_close(conn);
        return 0;
    }
    //不存在的话
    mysql_free_result(res);
    mysql_close(conn);
    return -1;
}

//检查md5码是否存在，实现秒传
int check_md5_exist(char* md5)
{
    MYSQL *conn;
    MYSQL_RES *res;
    MYSQL_ROW row;
    char query[300];
    sprintf(query,"select * from filepool where filemd5='%s';",md5);
    printf("%s\n",query);
    int ret = mySqlInit(&conn,query);
    res=mysql_use_result(conn);
    if((row=mysql_fetch_row(res))!=NULL)//MD5存在，返回0
    {
        mysql_free_result(res);
        mysql_close(conn);
        return 0;
    }
    //不存在的话
    mysql_free_result(res);
    mysql_close(conn);
    return -1;
}

//向数据库中插入文件
void insert_file(int precode,char* filename,int belongID,char* md5)
{
    MYSQL *conn;
    char query[300];
    sprintf(query,"insert into filelist(precode,code,filename,belongID,filetype,md5sum) value (%d,0,'%s',%d,'f','%s');",precode,filename,belongID,md5);
    int ret = mySqlInit(&conn,query);
    if(!ret)
        mysql_close(conn);
}

//增加文件的连接数
void linknum_add(char* filemd5)
{
    MYSQL *conn;
    MYSQL_RES *res;
    MYSQL_ROW row;
    char query[300];
    sprintf(query,"update filepool set linknum=linknum+1 where filemd5='%s';",filemd5);
        //printf("%s\n",query);
    int ret = mySqlInit(&conn,query);
    mysql_close(conn);
}